import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class ProductService {
    private List<Product> products = new ArrayList<>();
    private Integer nextId = 1;

    public ProductService() {
        initializeSampleProducts();
    }

    private void initializeSampleProducts() {
        products.add(new Product(nextId++, "iPhone 14", "苹果手机", 5999.0, 100));
        products.add(new Product(nextId++, "MacBook Pro", "苹果笔记本电脑", 12999.0, 50));
        products.add(new Product(nextId++, "AirPods", "无线耳机", 1299.0, 200));
        products.add(new Product(nextId++, "iPad", "平板电脑", 3299.0, 80));
    }

    public List<Product> getAllProducts() {
        return new ArrayList<>(products);
    }

    public Product getProductById(Integer id) {
        Optional<Product> product = products.stream()
                .filter(p -> p.getId().equals(id))
                .findFirst();
        return product.orElse(null);
    }

    public boolean addProduct(Product product) {
        product.setId(nextId++);
        return products.add(product);
    }

    public boolean updateStock(Integer productId, Integer quantity) {
        Product product = getProductById(productId);
        if (product != null && product.getStock() >= quantity) {
            product.setStock(product.getStock() - quantity);
            return true;
        }
        return false;
    }
}